package de.openlaboratory.elib.utilities;

import java.io.File;
import java.util.regex.Pattern;

import de.openlaboratory.elib.core.LogManager;

public class OpenLabUtilities
{
	/**
	 * Parse String and convert it to a Long using Long.parseLong. Exceptions
	 * are logged to the default Application Logger.
	 * @param s String to convert
	 * @return -1 if conversion fails<br>Long if successfully converted
	 */
	public static Long stringToLong(String s)
	{
		Long l = null;
		try
		{
			l = Long.parseLong(s.trim());
		}
		catch (NumberFormatException nfe)
		{
			LogManager.logMessage("stringToLong - NumberFormatException: " + nfe.getMessage());
		}
		catch (NullPointerException npe)
		{
			return (long) -1;
		}

		return l;
	}
	
	public static int stringToInt(String s)
	{
		int l = -1;
		try
		{
			l = Integer.parseInt(s.trim());
		}
		catch (NumberFormatException nfe)
		{
			LogManager.logMessage("stringToInt - NumberFormatException: " + nfe.getMessage());
		}
		catch (NullPointerException npe)
		{
			LogManager.logMessage("stringToInt - NullPointerException");
			return -1;
		}
		
		LogManager.logMessage("stringToInt: '" + s + "' -> " + l);

		return l;
	}
	

	public static Long[] stringToIDs(String[] v)
	{
		if (v == null || v.length == 0)
			return null;

		Long[] ids = new Long[v.length];

		for(int i=0; i < v.length; i++)
			ids[i] = stringToLong(v[i]);

		return ids;
	}

	public static String goUpInPath(String path, int levels)
	{
		return goUpInPath(path, levels, true);
	}
	
	public static String goUpInPath(String path, int levels, boolean trailingSeparator)
	{
		boolean unixishFilesystem = path.startsWith(File.separator);

		// TODO: Use path.getParentFile() repeatedly to get all components of a path.
		
		String[] directories = path.split(Pattern.quote(File.separator));
		String upperPath = path;

		
		if ((directories != null) && (directories.length > levels))
		{
			if (unixishFilesystem)
				upperPath = File.separator;
			else
				upperPath = "";
			
			for (int i = 0; i < directories.length - levels; i++)
			{
				if (directories[i] != null)
				{
					upperPath = upperPath.concat(directories[i]);
					if (trailingSeparator || (i < directories.length - levels - 1))
						upperPath = upperPath.concat(File.separator);
				}
			}
		}

		return upperPath;
	}
}